package com.ypc.webdemo.controller.dto;

import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.data.domain.Page;

import java.util.Collection;
import java.util.Collections;

/**
 * @author yinpengcheng
 * @Date 2023/7/21
 */
@Accessors(chain = true)
@Data
public class ServerResult<T> {
    private Integer code;
    private String message;
    private T data;

    public ServerResult(ServerCode serverCode, T data) {
        this.code = serverCode.getCode();
        this.message = serverCode.getMessage();
        this.data = data;
    }

    public static <T> ServerResult<T> success() {
        return new ServerResult<>(ServerCode.success, null);
    }

    public static <T> ServerResult<T> success(T data) {
        return new ServerResult<>(ServerCode.success, data);
    }

    public static <T> ServerResult<T> failure() {
        return new ServerResult<>(ServerCode.fail, null);
    }

    public static <T> ServerResult<T> failure(T data) {
        return new ServerResult<>(ServerCode.fail, data);
    }

    public static <T> ServerResult<T> result(ServerCode serverCode) {
        return new ServerResult<>(serverCode, null);
    }

    public static <T> ServerResult<T> notResult(T data) {
        return new ServerResult<>(ServerCode.not_result, data);
    }

    public static <T> ServerResult<PageDTO<T>> page(PageDTO<T> pageDTO) {
        return new ServerResult<>(ServerCode.success, pageDTO);
    }

    public static <T> ServerResult<PageDTO<T>> page(Page<T> page) {
        return new ServerResult<>(ServerCode.success, new PageDTO<>(page.getTotalElements(), page.getContent()));
    }

    @Getter
    @ToString
    public static class PageDTO<K> {
        private final Long total;
        private final Collection<K> items;

        public PageDTO(Long total, Collection<K> items) {
            this.total = null == total || total < 0 ? 0 : total;
            this.items = null == items ? Collections.emptyList() : items;
        }
    }


}
